package com.play.ballen.me.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.hjq.toast.ToastUtils
import com.play.ballen.R

class ModifyNickNameDialogUtils(private val mContext: Context) {

    val dialog: Dialog = Dialog(mContext)
    private lateinit var contentView: View
    private lateinit var edName: EditText

    private val mInputMethodManager by lazy {
        mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    }

    var valuesCallback: ((name: String) -> Unit)? = null

    fun show(name: String) {
        if (!this::contentView.isInitialized) {
            contentView =
                LayoutInflater.from(mContext).inflate(R.layout.dialog_modify_nickname, null)
            contentView.let {
                edName = it.findViewById(R.id.edName)

                it.findViewById<ImageView>(R.id.imgClose).setOnClickListener {
                    dialog.dismiss()
                }
                it.findViewById<ImageView>(R.id.imgClearText).setOnClickListener {
                    edName.text.clear()
                }
                it.findViewById<TextView>(R.id.btnOk).setOnClickListener {
                    if (edName.text.toString().isEmpty()) {
                        ToastUtils.show(edName.hint.toString())
                        return@setOnClickListener
                    }


                    val name = edName.text.toString()
                    dialog.dismiss()
                    valuesCallback?.invoke(name)
                }

                dialog.setContentView(it)
                dialog.setCanceledOnTouchOutside(false)
                dialog.window?.setLayout(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT
                )
                dialog.window?.setBackgroundDrawable(ColorDrawable())
                dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
                dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
            }
        }

        edName.setText(name)
        edName.setSelection(name.length)

        if (!dialog.isShowing) {
            dialog.show()

            edName.post {
                edName.requestFocus()
                mInputMethodManager.showSoftInput(edName, InputMethodManager.SHOW_IMPLICIT)
            }
        }
    }

}